<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="功能类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择功能类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.BT_GRID_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="功能参数（根据类型不同意义不同）" prop="params">
        <el-input v-model="formData.params" placeholder="请输入功能参数（根据类型不同意义不同）" />
      </el-form-item>
      <el-form-item label="背景图片（可无）" prop="bgImg">
        <div class="flex items-center">
          <el-input
            v-model="formData.bgImg"
            placeholder="请选择背景图片"
            readonly
            class="!w-240px mr-10px"
          />
          <el-button
            type="primary"
            plain
            @click="openImageSelect('bgImg')"
          >
            选择图片
          </el-button>
        </div>
        <el-image
          v-if="formData.bgImg"
          :src="formData.bgImg"
          class="mt-10px w-100px h-100px border"
          :preview-src-list="[formData.bgImg]"
        />
      </el-form-item>
      <el-form-item label="地块图片" prop="img">
        <div class="flex items-center">
          <el-input 
            v-model="formData.img" 
            placeholder="请选择地块图片" 
            readonly 
            class="!w-240px mr-10px"
          />
          <el-button 
            type="primary" 
            plain 
            @click="openImageSelect('img')"
          >
            选择图片
          </el-button>
        </div>
        <el-image
          v-if="formData.img"
          :src="formData.img"
          class="mt-10px w-100px h-100px border"
          :preview-src-list="[formData.img]"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>

  <!-- 在模板中添加 -->
  <FileImageSelectDialog ref="imageDialog" @select="handleImageSelect" />
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { GridApi, GridVO } from '@/api/bt/grid'
import FileImageSelectDialog from '@/views/infra/file/FileImageSelectDialog.vue'

// 在setup中声明ref
const imageDialog = ref<InstanceType<typeof FileImageSelectDialog>>()
import { ElImage } from 'element-plus'

/** 大富翁地块 表单 */
defineOptions({ name: 'GridForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  params: undefined,
  bgImg: undefined,
  img: undefined,
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const currentField = ref('') // 当前操作的图片字段

// 打开图片选择弹窗
const openImageSelect = (field: string) => {
  currentField.value = field
  imageDialog.value?.open()
}

// 处理图片选择
const handleImageSelect = (file) => {
  if (currentField.value) {
    formData.value[currentField.value] = file.url
    currentField.value = '' // 清空当前字段
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GridApi.getGrid(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as GridVO
    if (formType.value === 'create') {
      await GridApi.createGrid(data)
      message.success(t('common.createSuccess'))
    } else {
      await GridApi.updateGrid(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    params: undefined,
    bgImg: undefined,
    img: undefined,
  }
  formRef.value?.resetFields()
}
</script>